package org.zzz.hepotaiya.executor;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.zzz.hepotaiya.beans.BatchInfo;
import org.zzz.hepotaiya.beans.BatchResult;
import org.zzz.hepotaiya.enums.ResultType;
import org.zzz.hepotaiya.util.ResourceUtil;

public class SimpleExecutor extends AbstractExecutor implements BatchExecutor {

	private static final Logger logger = Logger.getLogger(SimpleExecutor.class);
	
	/*
	 * (non-Javadoc)
	 * @see org.zzz.hepotaiya.executor.BatchExecutor#doExecute(java.lang.String)
	 */
	public List<BatchResult> doExecute(String batchRootPackage) throws Exception {
		super.setUp();
		// バッチ読み込み
		Map<Integer, List<BatchInfo>> map = this.batchLoader.load(batchRootPackage, super.getConfigList());

		if (logger.isDebugEnabled()) {
			logger.debug(ResourceUtil.getString("executor.log.loaded"));
		}
		// フェーズ毎にバッチリスト取得
		for (int phase = 0; phase <= map.size(); phase++) {
			List<BatchInfo> list = map.get(phase);
			if (list == null) {
				continue;
			}
			if (logger.isDebugEnabled()) {
				logger.debug(ResourceUtil.getString("executor.log.phase.start", phase));
			}

			for (BatchInfo info : list) {
				// 依存確認
				String skipCause = super.checkDepency(info.getDependencies());
				if (!StringUtils.isEmpty(skipCause)) {
					info.setResultType(ResultType.SKIP);
					super.resultList.add(info);
					continue;
				}
				if (logger.isDebugEnabled()) {
					logger.debug(ResourceUtil.getString("executor.log.call", info.getBatchName()));
				}
				// 実行
				info.setReturnObject(info.getTargetMethod().invoke(info.getTargetObject(), (Object[])null));
				// 実行結果設定
				info.dispatchResultType(info.getTargetMethod().getReturnType(), info.getReturnObject());
				
				// 結果セット
				super.resultList.add(info);
				super.resultMap.put(info.getBatchName(), info.getResultType() == ResultType.SUCCESS);
				
				if (info.getResultType() == ResultType.FAILURE && info.isErrorStop()) {
					return super.resultList;
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug(ResourceUtil.getString("executor.log.phase.end", phase));
			}
		}
		return super.resultList;
	}
}
